package com.example.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;

/**
 * 前端请求到达服务器
 * ↓
 * Interceptor.preHandle()      【请求前】
 * ↓ (返回true则继续执行，返回false则中断请求)
 * Controller 方法执行
 * ↓
 * Interceptor.postHandle()     【请求后，视图渲染前】
 * ↓
 * View视图渲染完成（响应生成）
 * ↓
 * Interceptor.afterCompletion()【请求完成后】
 * ↓
 * 响应返回给前端
 */

/**
 * 自定义的拦截器：实现根据IP统计访问次数
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 访问的ip
        String ip = request.getRemoteAddr();
        // 统计访问次数并输出
        HttpSession session = request.getSession();
        Integer count = (Integer) session.getAttribute("count");
        count = Objects.isNull(count) ? 1 : ++count;
        System.out.println("ip: " + ip + " count: " + count);
        session.setAttribute("count", count);
        // 放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
